package cn.com.victorysoft.filter;

import cn.com.victorysoft.base.BaseInfoProperties;
import cn.com.victorysoft.result.GraceJSONResult;
import cn.com.victorysoft.result.ResponseStatusEnum;
import cn.com.victorysoft.utils.IPUtil;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @Description:
 *         判断某个请求的ip在20s内的请求次数是否超过3次
 *         如果超过3次,则限制该ip的访问
 *         等待30秒后,再允许该ip的访问
 * @Author: 张广焱
 * @Date: 2025-03-23 19:50
 */
@Component
public class IPLimitFilter extends BaseInfoProperties implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(IPLimitFilter.class);

    @Value("${blackIp.continueCounts:100}")
    private Integer continueCounts;

    @Value("${blackIp.timeInterval:100}")
    private Integer timeInterval;

    @Value("${blackIp.limitTimes:100}")
    private Integer limitTimes;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("IPLimitFilter 当前的执行顺序order为1");
        log.info("continueCounts: {}", continueCounts);
        log.info("timeInterval: {}", timeInterval);
        log.info("limitTimes: {}", limitTimes);

        return doLimit(exchange, chain);
    }
    private Mono<Void> doLimit(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求的ip
        ServerHttpRequest request = exchange.getRequest();
        String ip = IPUtil.getIP(request);

        // 正常的ip定义
        final String ipRedisKey = "gateway-ip:" + ip;
        // 被拦截的黑名单ip，如果在redis中存在，则表示目前被关小黑屋
        final String ipRedisLimitKey = "gateway-ip:limit:" + ip;
        //获得当前ip并且查询还剩多少时间，如果还剩的时间大于0，则表示还在黑名单中
        Long ipLimitTime = redis.ttl(ipRedisKey);
        if (ipLimitTime != null && ipLimitTime > 0) {
            return renderErrorMsg(exchange,ResponseStatusEnum.SYSTEM_ERROR_BLACK_IP);
        }
        //在redis中获得ip的累加次数
        long requestCounts = redis.increment(ipRedisKey, 1);

        /**
         * 判断如果是第一次进来，也就是从0开始计数，则初期访问就是1，
         * 需要设置间隔的时间，也就是连续请求的次数的间隔时间
         */
        if (requestCounts == 1) {
            redis.expire(ipRedisKey, timeInterval);
        }

        /**
         * 如果还能获得请求的正常次数，说明用户的连续请求落在限定的[timeInterval]之内
         * 一旦请求次数超过限定的连续访问次数[continueCounts]，则需要限制当前的ip
         */
        if (requestCounts > continueCounts) {
            // 限制ip访问的时间[limitTimes]
            redis.set(ipRedisLimitKey, ipRedisLimitKey, limitTimes);
            // 终止请求，返回错误
            return renderErrorMsg(exchange, ResponseStatusEnum.SYSTEM_ERROR_BLACK_IP);
        }

        return chain.filter(exchange);
    }
    /**
     * @param exchange   交换
     * @param statusEnum 状态枚举
     * @Description: 重新包装并且返回新的错误信息
     * @Author: 张广焱
     * @Date: 2025-03-23  20:26:49
     */
    public Mono<Void> renderErrorMsg(ServerWebExchange exchange, ResponseStatusEnum statusEnum) {
//        1.获取相应的response
        ServerHttpResponse response = exchange.getResponse();
        //2.构建jsonResult
        GraceJSONResult jsonResult = GraceJSONResult.exception(statusEnum);
        // 3. 设置header类型
        if (!response.getHeaders().containsKey("Content-Type")) {
            response.getHeaders().add("Content-Type",
                    MimeTypeUtils.APPLICATION_JSON_VALUE);
        }
        //4.修改response的状态码为500
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        //5.转换json并且像response中写入数据
        String resultJson = new Gson().toJson(jsonResult);
        DataBuffer wrap = response.bufferFactory()
                .wrap(resultJson.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(wrap));
    }


    @Override
    public int getOrder() {
        return 1;
    }
}
